<template>
  <div :class="['cata-wrapper', {'preview-page': isPreview}]">
        <!-- <BreadCrumb :list="crumbList"></BreadCrumb> -->
        <div class="preview-tag-wrap" v-if="isPreview">
            <i class="iconfont icon-tishi"></i>
            <span class="text">当前为预览状态，请不要进行操作，操作无效</span>
        </div>
        <div class="cata-wrapper-top">
           <div class="cata-wrapper-left" v-loading="loading">
               <!-- 素材库 -->
               <template v-if="courseDetail.contentType === 'material'">
                   <!-- 视频 -->
                   <Video ref="videoRef" v-if="courseDetail.materialVO?.materialType === 'video' && courseDetail.materialVO?.materialStatus === 'usable' && currentUser?.userId" :video-data="courseDetail.materialVO" :detail="courseDetail"/>
                   <!-- 其他资源 -->
                   <FileView ref="fileRef" v-else-if="courseDetail.materialVO?.materialType !== 'video' && courseDetail.materialVO?.materialStatus === 'usable'" :fileData="courseDetail.materialVO" :detail="courseDetail"/>
                   <FileError ref="fileRef" v-else :fileData="courseDetail.materialVO"/>
               </template>
               <template v-if="courseDetail.contentType === 'comment'">
                    <div class="discuss-info">
                        <p class="discuss-title">
                            <img src="@/assets/img/mooc/discuss-icon.png" alt="">
                            <Ellipsis :content="courseDetail.contentTitle"/>
                        </p>
                        <p class="desc" v-if="courseDetail?.contentExtend?.desc">{{courseDetail?.contentExtend?.desc}}</p>
                        <p class="must-join" v-if="courseDetail.isMust == 1">
                            <i class="iconfont icon-a-tiaojian1x"></i>
                            <span>必须参与讨论</span>
                        </p>
                    </div>
               </template>
               <div class="cata-wrapper-bottom" v-if="showDisscuss">
                    <template v-if="isBuyPerson || isPreview">
                        <div class="send-comment">
                            <h2 class="bottom-header">我要讨论</h2>
                            <addDiscuss @update:list="refreshList" :is-preview="isPreview"/>
                        </div>
                    </template>
                    <div class="comment-container">
                        <h2 class="bottom-header">全部讨论</h2>
                        <DiscussWrap
                            ref="bottomRef"
                            :detail="detailData"
                            :is-buy-person="isBuyPerson"
                            :is-creater="isCreater" 
                            :is-preview="isPreview"
                        />
                    </div>
                </div>
           </div>
           <div class="cata-wrapper-right">
               <el-tabs v-model="currentTab">
                   <el-tab-pane
                       v-for="tab in rightTab" 
                       :key="tab.key"
                       :label="tab.name"
                       :name="tab.key">
                   </el-tab-pane>
               </el-tabs> 
               <div class="cata-wrapper-container">
                    <component 
                        :is="componentMap[currentTab]" 
                        :current-tab="currentTab" 
                        ref="comRef" 
                        :detail="detailData" 
                        :tool-detail="toolDetail" 
                        :is-buy-person="isBuyPerson" 
                        :is-creater="isCreater" 
                        :is-preview="isPreview" 
                        :courseWare-state-list="courseWareStateList"
                        @change-catalogue="changeCatalogue" 
                        @start-video="startVideo"
                    >
                    </component> 
               </div>
           </div>
        </div>
        <!-- <div class="cata-wrapper-bottom" v-if="showDisscuss">
            <h2 class="bottom-header">讨论</h2>
            <DiscussWrap ref="bottomRef" :detail="detailData" :is-buy-person="isBuyPerson" :is-creater="isCreater" :is-preview="isPreview"/>
        </div>   -->
  </div>
</template>
<script setup>
import BreadCrumb from '@/components/bread-crumb.vue';
import Video from './part/video-cell.vue'; // 视频
import FileView from './part/file-view.vue'; // 素材库
import FileError from './part/file-error.vue'; // 素材库
import CourseCatalogue from '@/views/catalogue-detail/fragment/course-catalogue/index.vue'; // 课程目录
import DiscussWrap from './fragment/discuss-wrap/index.vue';
import addDiscuss from './fragment/discuss-wrap/discuss/add.vue';
import Ellipsis from '@/components/ellipsis.vue'
import { ref, onMounted, computed, nextTick, watch, watchEffect, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { queryToJson, deepCopy } from '@/lib/tools';
import useReport from '@/hooks/useReport.js';

const route = useRoute();
const router = useRouter();
const report = useReport();

const store= useStore();

const loading = ref(false);

const rightTab = ref([
    {
        name: '课程目录',
        key: 'course-catalogue',
        visible: true
    }
]);

// 当前选中的tab
const currentTab = ref('course-catalogue');


const componentMap = {
    'course-catalogue': CourseCatalogue
}

const currentUser = computed(() => {
    return store.state.currentUser || {}
})

// 判断是否登录
const isLogin = computed(() => {
    return store.state.isLogin;
})

// 是否显示讨论
const showDisscuss = computed(() => {
    let pagePermission = store.state?.pagePermission || {};
    return !!pagePermission['moocApplication:interactive:discuss']
})

// 课件详情
const courseDetail = ref({});

// 更改目录 参数1：目录id 参数2： 课件信息
function changeCatalogue(catalogueId, courseWare) {
    courseDetail.value = courseWare || {};
    window.history.replaceState('', '', `?catalogueId=${catalogueId}&courseId=${route.query.courseId}`);
    getCourseByCatalogue(catalogueId);
}

// 慕课详情
const detailData = ref({});

// 是否是创建者
const isCreater = computed(() => {
    return detailData.value?.isMyCreate;
})

// 是否是购买者
const isBuyPerson = computed(() => {
    return detailData.value?.isBuy;
})

// 是否是管理员 是否是从管理中心进入的页面
const isManage = ref(false);

// 面包屑
const crumbList = ref([
    {
        name: '',
        route: {
            name: 'detail',
            params: {
                moocId: route.params.moocId
            },
        }
    }
]);

const errorMsgMap = {
    'delete': '很抱歉，该慕课已下线', // 删除
    'disabled': '很抱歉，该慕课已下线', // 禁用
    'unpublished': '很抱歉，当前慕课还未发布，敬请期待', // 未发布
    'notsignup': '还未报名慕课哦，请先报名', // 没报名
    'noauthority': '很抱歉，您暂无查看权限', // 没权限
    'deleteCatelogue': '该课件可能已经被删除' // 课件被删除
}

// 是否是预览状态
const isPreview = ref(false);

function refreshList(){
    bottomRef.value && bottomRef.value.refresh();
}

// 获取课程详情
async function getCourseDetail() {
    try {
        let res = await  G_transmit('moocDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })

        detailData.value = res.data || {};

        crumbList.value[0].name = detailData.value?.title || '';

        // 不是购买者 并且不是创建人
        let notCourseUser = !detailData.value?.isBuy && !detailData.value?.isMyCreate;

        let isPublish = detailData.value?.publishState == 1 && detailData.value?.state == 4;

        // 课程未发布 除创建人和已经报名的人都不能看
        let moocSquare = '/idx/mooc/square';
        if (!isPublish && notCourseUser) {
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.unpublished, code: 500, target: moocSquare, buttonLabel: '查看其他慕课'});
        }
        // 慕课发布了 除创建人和已经报名的人都不能看
        if(notCourseUser) {
           let href = router.resolve({
              ...crumbList.value[0].route
           }).href;
           G_dispatchEvent('toErrorPage', { title: errorMsgMap.notsignup, code: 500, target: href, buttonLabel: '去报名'});
        }
    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        let moocSquare = '/idx/mooc/square';
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.delete, code: 500, target: moocSquare, buttonLabel: '查看其他慕课'});
        }  else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}


const comRef = ref(null);


const bottomRef = ref(null);


// 获取听评课或者案例第三步设置信息
const toolDetail = ref({});

const videoRef = ref(null);

const fileRef = ref(null);

// 开始播放视频
function startVideo(item) {
    window.scrollTo(0, 0);
    videoRef.value && videoRef.value.startVideo(item);   
}

// 后端获取课程详情
// state 状态（0-暂存、1-提交（待提审）、2-待审核、3-审核驳回、4-审核通过）
// publishState 发布状态（0-未发布 1-已发布）
// enable 是否启用 1启用 -1禁用
async function getManageDetail () {
    try {
        let res = await G_transmit('moocManageDetail', {
            queries: {
                id: route.params.moocId
            },
            silence: true
        })
        detailData.value = res.data || {};
        crumbList.value[0].name = detailData.value.title;

    } catch(_err) {
        // 禁用课程 30800500 删除课程 30800404
        let moocSquare = '/idx/mooc/square';
        if (_err.status && _err.status.code && [30800500, 30800404].includes(_err.status.code)) {
            G_dispatchEvent('toErrorPage', { title:  errorMsgMap.delete, code: 500, target: moocSquare, buttonLabel: '查看其他慕课'});
        } else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    }
}

// 获取管理权限
async function getManageAuth () {
    try {
        await G_transmit('checkPermissionByKeyAndUserId', {
            queries: {
                permissionkey: 'siteAdmin:application:mooc:courseMange', // 慕课课程管理菜单的key 有菜单权限表示能查看详情页
                userId: store.state?.currentUser?.userId
            },
            silence: true
        })
    } catch(_err) {
        isManage.value = _err == 1;
        if (isManage.value) { // 管理员请求的详情和普通人不一样
            await getManageDetail();
            getCourseByCatalogue();
        } else {
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.noauthority, code: 500});
        }
    }
}

// 获取课件信息
function getCourseByCatalogue(catalogueId = '') {
    courseDetail.value = {};
    loading.value = true;
    G_transmit('courseContentDetail', {
        queries: {
            id: catalogueId || queryToJson().catalogueId // 目录id // 课程id
        },
        silence: true
    }).then(async (res) => {
        await getSubTitle(res.data.contentId);
        let data = res.data || {};
        data = Object.assign(data, {textTrack: subTitleList.value});
        if(data.contentType == 'comment'){
            data.contentExtend = data.contentExtend && JSON.parse(data.contentExtend) || ''
        }
        courseDetail.value = deepCopy(data);
        loading.value = false;

        let item = {
            name: courseDetail.value.contentTitle,
            route: {}
        };
        if (crumbList.value.length > 1) {
            crumbList.value[1] = item;
        } else {
            crumbList.value.push(item);
        }

        store.dispatch('setBreadCrumb', crumbList.value);
        
        nextTick(async() => {
            // 是购买人，并且不是预览状态
            if (detailData.value?.isBuy && !isPreview.value && courseDetail.value?.materialVO?.materialStatus && courseDetail.value?.materialVO?.materialStatus === 'usable') {
                if (courseDetail.value?.materialVO?.materialType === 'video') {
                    console.log('video==================')
                    videoRef.value && videoRef.value.startRecord('offline');
                    await nextTick();
                    getCourseWareStatusInfo();
                } else {
                    fileRef.value && fileRef.value.startRecord('offline');
                    console.log('doc====================')
                    await nextTick();
                    getCourseWareStatusInfo();
                }
                
            }
            bottomRef.value && bottomRef.value.refresh();
        })
    }).catch(_err => {
        loading.value = false;
        if (_err.status && _err.status.code && [10000002].includes(_err.status.code)) { // 目录不存在
            let href = router.resolve({
              ...crumbList.value[0].route
           }).href;
            G_dispatchEvent('toErrorPage', { title: errorMsgMap.deleteCatelogue, code: 500, target: href, buttonLabel: '返回慕课详情'});
        } else {
            G_dispatchEvent('toast', { message: _err?.status?.desc || '服务开小差了～', type: 'error'});
        }
    })
}

const courseWareStateList = ref([]) // tree课件对应状态集合

// 获取课件完成状态进度等信息
async function getCourseWareStatusInfo() {
    if (!route.params?.moocId || !route.query?.courseId) {
        return;
    }
    try {
        let res = await G_transmit('courseWareStatus', {
            data: {
                courseId: route.query.courseId, // 课程id
                moocId: route.params.moocId 
            }
       })
       courseWareStateList.value = []
       await nextTick()
       courseWareStateList.value = res.data || [];
       
   } catch (_err) {
       loading.value = false;
       console.log(_err);
   }
}

// 字幕
const subTitleList = [];

// 获取字幕
function getSubTitle(id) {
    let materialId = id || '';
    if(!materialId) {
        return [];
    }
    return G_transmit('subtitleSearch', {
        data: {
            materialIds: [materialId],
            subtitleType: 'vtt',
        },
        silence: true
    }).then((res) => {
        let list = (res.data || []).map((item, index) => {
            let temp = {
                src: item.subtitleUrl,
                kind: "subtitles",
                label: '字幕' + (index + 1),
                srclang: 'zh',
                default: index === 0
            }
            return temp;
        })
        subTitleList.value = list;
        // videoRef.value?.setSubTitle(list);
    }).catch(_err => {
        console.log(_err);
    })
}

let pathNameMap = {
    'catalogueDetail': 'detail',
    'manageCatalogueDetail': 'manageDetail',
    'previewCatalogueDetail': 'previewDetail',
    'strainCatalogueDetail': 'strainDetail',
}

onMounted(async () => {
    await store.dispatch('checkIsLogout');
    if (route.name !== 'manageCatalogueDetail') { // 不是从管理端进入的
        crumbList.value[0].route.name = pathNameMap[route.name];
        isPreview.value = route.name === 'previewCatalogueDetail';
        await getCourseDetail();
        getCourseByCatalogue();
        getCourseWareStatusInfo();
    }
    
})

// 监听个人信息变化
watch(() => store.state.currentUser, (val) => {
    if (Object.keys(val).length !== 0) {
        if (route.name === 'manageCatalogueDetail') { // 从管理端进入的
            crumbList.value[0].route.name = pathNameMap[route.name];
            getManageAuth();
        }
    }
}, {immediate: true});

// 全部备案信息
const brand = computed(() => {
    return store.state.brand && store.state.brand.publishBrand ? store.state.brand.publishBrand : {};
})

// 具体备案信息
const brandInfo = computed(() => {
    return brand.value.brandConfig ? brand.value.brandConfig : {};
})

watchEffect(() => {
    let lessonName = detailData.value?.title ? detailData.value?.title : '';
    let siteName = brandInfo.value?.siteName ? '-' + brandInfo.value?.siteName : ''
    document.title = lessonName + siteName
})

</script>

<style lang="scss" scoped>
.preview-page {
    margin-top: -8px;
}
.preview-tag-wrap {
    height: 34px;
    background: #FFF7EB;
    border-radius: 4px;
    border: 1px solid #FFEFD9;
    margin: -4px 0 16px 0;
    display: flex;
    align-items: center;
    color: #BA6009;
    font-size: 14px;
    padding: 0 10px;
    font-family: MicrosoftYaHei;
    .iconfont {
        font-size: 18px;
        color: var(--srt-color-warning);
        margin-right: 6px;
        margin-top: -2px;
    }
    .text {
        line-height: 32px;
    }
}
.cata-wrapper-top {
    display: flex;
    border-radius: 4px;
    overflow: hidden;
    .video-wrapper {
        width: 793px;
    }
    .cata-wrapper-left {
        width: 793px;
        min-height: 458px;
        margin-right: 20px;
    }
    .cata-wrapper-right {
        width: 387px;
        height: 447px;
        background: #ffffff;
        box-sizing: border-box;
        :deep(.el-tabs) {
            margin: 0px 20px;
        }
        :deep(.el-tabs__item) {
            height: 60px;
            line-height: 60px;
            font-size: 16px;
            font-weight: 400;
            color: var(--srt-main-text-color);
            box-shadow: none;
            &.is-active {
                font-weight: bold;
                color: var(--srt-main-active-text-color)
            }
        }
        :deep(.el-tabs__active-bar) {
           height: 3px;
        }
        :deep(.el-tabs__nav-wrap) {
            &::after {
                height: 1px;
            }
        }
    }
    .cata-wrapper-container {
        height: calc(100% - 80px);
        overflow-y: auto;
       
    }
    :deep(.xg-text-track) {
        font-size: 26px !important;
    }
    :deep(.xgplayer-is-fullscreen) {
        .xg-text-track {
           font-size: 45px !important;
        }
    }
}

.cata-wrapper-bottom {
    // background: #ffffff;
    min-height: 600px;
    margin-top: 20px;
    // padding: 20px 20px 30px;
    border-radius: 4px;
    .bottom-header {
        font-size: 16px;
        line-height: 16px;
        font-family: MicrosoftYaHei-Bold, MicrosoftYaHei;
        font-weight: bold;
        color: #000000;
        margin-bottom: 14px;
        &::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 16px;
            background-color: var(--srt-main-active-text-color);
            margin-right: 6px;
            vertical-align: middle;
        }
    }
}
.send-comment,.comment-container{
    background: #ffffff;
    padding: 20px 20px 30px;
    border-radius: 4px;
}
.send-comment{
    margin-bottom: 20px;
}
.discuss-info{
    width: 100%;
    padding: 16px 15px 20px;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 4px;
    .discuss-title{
        font-size: 18px;
        font-weight: bold;
        color: #222222;
        line-height: 28px;
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        img{
           width:28px; 
           height:28px;
           margin-right: 4px;
        }
    }
    .desc{
        font-size: 14px;
        color: #222222;
        line-height: 22px;
        word-break: break-all;
    }
    .must-join{
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #222222;
        line-height: 18px;
        margin-top: 6px;
        i{
            font-size: 12px;
            margin-right: 6px;
        }
    }
}
.el-tag{
    width:100%;
    height: 34px;
    justify-content: flex-start;
    margin-bottom: 16px;
}
.warn{
    width:100%;
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #BA6009;
    img{
        width:18px;
        height:18px;
        margin-right: 6px;
    }
}
</style>